﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using FinalTestMachine.Motion.Aixs;
using FinalTestMachine.Motion.Process;
using LanguageControlBase.Wpf;

namespace FinalTestMachine.View.MainUnits
{
    /// <summary>
    /// Wnd_TestStation.xaml 的交互逻辑
    /// </summary>
    public partial class Wnd_TestStation : Window
    {
        static readonly object ob_lock = new object();
        static Wnd_TestStation Cur = null;
        private Wnd_TestStation()
        {
            InitializeComponent();

            CreateUI();
        }
        private List<TextBlock> testStatus = new List<TextBlock>();
        TextBlock GetStatus(int index)
        {
            return testStatus[index];
        }
        private List<TextBlock> testTime = new List<TextBlock>();
        TextBlock GetTime(int index)
        {
            return testTime[index];
        }
        private List<LanButton> testStart = new List<LanButton>();
        LanButton GetStart(int index)
        {
            return testStart[index];
        }
        private void CreateUI()
        {
            for (int i = 0; i < GlobalParams.WorkstationSum; i++) {
                grid_testDemo.RowDefinitions.Add(new RowDefinition());
                LanTextBlock lanTextBlock = new LanTextBlock()
                {
                    HorizontalAlignment = HorizontalAlignment.Center, 
                    VerticalAlignment = VerticalAlignment.Center,
                    Background = Brushes.LightYellow,
                    FontSize = 12,
                    FontWeight = FontWeights.Bold,
                    LanText = "工位" + (i+1)
                };
                Grid.SetRow(lanTextBlock, i + 1);
                Grid.SetColumn(lanTextBlock, 0);
                grid_testDemo.Children.Add(lanTextBlock);

                Border site2TestStateBorder = new Border
                {
                    Margin = new Thickness(20, 0, 0, 0),
                    //Height = 15,
                    //HorizontalAlignment = HorizontalAlignment.Center,
                    VerticalAlignment = VerticalAlignment.Center,
                };
                Grid.SetRow(site2TestStateBorder, i+1);
                Grid.SetColumn(site2TestStateBorder, 1);

                TextBlock tbSite2TestState = new TextBlock
                {
                    //HorizontalAlignment = HorizontalAlignment.Center,
                    //VerticalAlignment = VerticalAlignment.Center,
                    Background = Brushes.Green,
                    Width = 45,
                    
                    FontSize = 12,
                    Text = "Pass",
                    TextAlignment = TextAlignment.Center
                };
                testStatus.Add(tbSite2TestState);
                site2TestStateBorder.Child = tbSite2TestState;

                TextBlock tbSite2TestTime = new TextBlock
                {
                    HorizontalAlignment = HorizontalAlignment.Center,
                    VerticalAlignment = VerticalAlignment.Center,
                    Text = "10",
                };
                testTime.Add(tbSite2TestTime);

                Grid.SetRow(tbSite2TestTime, i + 1);
                Grid.SetColumn(tbSite2TestTime, 2);

                // 创建测试按钮
                LanButton btnSite2StartTest = new LanButton
                {
                    Name = "btn_Site2StartTest",
                    Width = 60,
                    Height = 30,
                    LanContent = "测试",
                    Margin = new Thickness(0,0,0,2)
                };
                testStart.Add(btnSite2StartTest);
                Grid.SetRow(btnSite2StartTest, i + 1);
                Grid.SetColumn(btnSite2StartTest, 3);
                int index = i;
                btnSite2StartTest.Click += (s,e) =>
                {
                    if (!Motion.StaticInitial.Motion.CurOrder.IsAutoRunning)
                    {
                        SaveBeginInvoke(() => Process_TestStationBase.testStaionList[index].TestStart(true));
                    }
                };

                /*// 创建发送按钮
                LanButton btnSite2Send = new LanButton
                {
                    Name = "btn_Site2Send",
                    Width = 60,
                    Height = 30,
                    Margin = new Thickness(0, 0, 0, 2),
                    LanContent = "发送",
                };
                Grid.SetRow(btnSite2Send, i+1);
                Grid.SetColumn(btnSite2Send, 5);
                btnSite2Send.Click += (s,e) =>
                {
                    if (Motion.StaticInitial.Motion.CurOrder.IsAutoRunning)
                    {
                        SaveBeginInvoke(() => Process_TestStationBase.testStaionList[index].Run());
                    }
                    else
                    {
                        SaveBeginInvoke(() => Process_TestStationBase.testStaionList[index].TestStart(true));
                    }
                };*/

                // 将控件添加到父容器中
                // 假设您的Grid名为mainGrid
                grid_testDemo.Children.Add(site2TestStateBorder);
                grid_testDemo.Children.Add(tbSite2TestTime);
                grid_testDemo.Children.Add(btnSite2StartTest);
                //grid_testDemo.Children.Add(btnSite2Send);
            }
        }

        public static Wnd_TestStation CreateInstrance()
        {
            if (Cur == null)
            {
                lock (ob_lock)
                {
                    if (Cur == null)
                    {
                        Cur = new Wnd_TestStation();
                    }
                }
            }

            return Cur;
        }

        public static void SingleShow()
        {
            Window window = CreateInstrance();
            window.Owner = App.Current.MainWindow;
            window.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            window.WindowState = WindowState.Normal;
            window.Show();

        }

        bool IsExit = false;
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Task.Run(() => ShowUI());
        }
        private void Window_Closed(object sender, EventArgs e)
        {
            Cur = null;
            IsExit = true;
        }

        void ShowUI()
        {
            bool IsCanScan = true;
            void SetState(Process_TestStationBase testStation, TextBlock tb_TestState, TextBlock tb_TestTime, Button btn_Test)
            {
                if (testStation.IsProcessRunning)
                {
                    tb_TestState.Text = "测试中";
                    tb_TestState.Background = Brushes.Yellow;
                    tb_TestTime.Text = testStation.TestTime.ToString("F3");
                    btn_Test.IsEnabled = false;
                }
                else
                {
                    btn_Test.IsEnabled = true;
                    if (testStation.IsTestOK)
                    {
                        tb_TestState.Text = "Pass";
                        tb_TestState.Background = Brushes.Green;
                    }
                    else
                    {
                        tb_TestState.Text = "Fail";
                        tb_TestState.Background = Brushes.Red;
                        tb_TestTime.Text = testStation.TestTime.ToString("F3");
                    }
                }
            }

            while (!IsExit)
            {
                if (IsCanScan)
                {
                    IsCanScan = false;
                    this.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        try
                        {
                            for (int i = 0; i < GlobalParams.WorkstationSum; i++)
                            {
                                SetState(Process_TestStationBase.testStaionList[i], GetStatus(i), GetTime(i), GetStart(i));
                            }
                        }
                        catch (Exception ex) {
                            MessageBox.Show($"手动创建的测试站数量{Process_TestStationBase.testStaionList.Count}低于系统参数中{GlobalParams.WorkstationSum}所设定的！");
                            IsExit = true;
                        }
                        

                        if (!RotatedMovNextHelper.IsOkPos || Aix_Turn.Cur.IsBusy || Aix_Turn.Cur.GetAixRunState())
                        {
                            for(int i = 0; i < GlobalParams.WorkstationSum; i++)
                            {
                                testStart[i].IsEnabled = false;
                            }
                        }
                        IsCanScan = true;
                    }));
                }

                Thread.Sleep(100);
            }

        }
        private Action SaveBeginInvokeAction;

        private void SaveBeginInvoke(Action action)
        {
            void SaveInvoke(Action action1)
            {
                try
                {
                    action1?.Invoke();
                }
                catch (Exception ex)
                {
                    string get(Exception ex1)
                    {
                        if (ex1.InnerException == null)
                        {
                            return ex1.Message;
                            // return;
                        }
                        return get(ex1.InnerException);
                    }

                    this.Dispatcher.Invoke(() =>
                    {
                        MessageBox.Show(get(ex));
                    });
                }
            }

            try
            {
                SaveBeginInvokeAction = () => SaveInvoke(action);
                SaveBeginInvokeAction.BeginInvoke(null, null);
            }
            catch (Exception ex)
            {
                string get(Exception ex1)
                {
                    if (ex1.InnerException == null)
                    {
                        return ex1.Message;
                        // return;
                    }
                    return get(ex1.InnerException);
                }

                this.Dispatcher.Invoke(() =>
                {
                    MessageBox.Show(get(ex));
                });
            }
        }
    }
}
